#include "EventLoopThread.h"
#include "EventLoop.h"
#include <functional>
#include <assert.h>
#include "util.h"

EventLoopThread::EventLoopThread()
    : loop_(NULL),
    exiting_(false),
    thread_(),
    mutex_(),
    cond_() {}

EventLoopThread::~EventLoopThread()
{
    exiting_ = true;
    loop_->quit();
    thread_.join();
}

std::thread::id EventLoopThread::tid() { return loop_->getTid(); }

// 返回已创建好并在一个线程中开始loop的EventLoop
EventLoop* EventLoopThread::startLoop()
{
    thread_ = thread(bind(&EventLoopThread::threadFunc, this));

    {
        unique_lock<mutex> lock(mutex_);
        while (loop_ == NULL)
        {
            cond_.wait(lock);
        }
    }

    return loop_;
}

// 创建EventLoop并开始loop
void EventLoopThread::threadFunc()
{
    EventLoop loop;

    {
        unique_lock<mutex> lock(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }

    loop.loop();
    assert(exiting_);
    loop_ = NULL;
}